using System;
using System.Data;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;

namespace Stratman.Web.VSTS
{
    /// <summary>
    /// Displays an administration page allowing the user to browse the timesheets of all users in the system or
    /// jump directly to timesheets that are waiting to be approved.
    /// </summary>
    public partial class TimesheetAdmin : Page
    {
        /// <summary>
        /// Event handler that is invoked when the page is loaded; here we get a list timesheets awaiting approval
        /// and write the information to a bulleted list.
        /// </summary>
        /// <param name="sender">
        /// Object from which this event originated.
        /// </param>
        /// <param name="e">
        /// Arguments associated with this event.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Check to make sure that the user is an administrator before giving them access
            if (!IsUserAdministrator(Request.LogonUserIdentity.Name))
            {
                is1.Initialize();
                ph1.LoadHeaderDetails(fo1, new string[] { "<a href=\"index.aspx\">Home</a>" }, 5, base.IsPostBack, null);

                problemsPanel.Visible = true;
                contentPanel.Visible = false;
                problemsLiteral.Text = "You do not have access to the timesheet administrative features.";

                return;
            }

            // Initialize the breadcrumbs and the toolbar
            Menu[] menus = ToolbarCreator.GetToolbar(ToolbarItems.EditQuery);
            menus[0].Items[0].Text = "&nbsp;My Timesheet";
            menus[0].Items[0].NavigateUrl = "timesheet.aspx";

            is1.Initialize();
            ph1.LoadHeaderDetails(fo1, new string[] { "<a href=\"index.aspx\">Home</a>", "Timesheet Administration" }, 5, base.IsPostBack, menus);
            hh1.PageTitle = "Timesheet Administration";

            // Get a list of timesheets awaiting approval
            SqlConnection databaseConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["TimesheetDatabase"].ConnectionString);
            SqlCommand command = new SqlCommand("usp_RS_AwaitingApproval", databaseConnection);

            command.CommandType = CommandType.StoredProcedure;
            databaseConnection.Open();
            lit1.Text += "<ul>";

            SqlDataReader reader = command.ExecuteReader();
            string currentSid = "";

            while (reader.Read())
            {
                // Emit a nested, bulleted list containing a parent bullet for each user and then children for the
                // timesheets that are awaiting approval
                string sid = (string)reader["sid"];
                DateTime weekStarting = (DateTime)reader["weekStarting"];
                
                if (sid != currentSid)
                {
                    if (currentSid != "")
                        lit1.Text += "</ul></li>";

                    DirectoryEntry userInfo = new DirectoryEntry("LDAP://<SID=" + sid + ">");

                    lit1.Text += "<li><a href=\"timesheet.aspx?u=" + sid + "\">" + userInfo.Properties["cn"].Value.ToString() + "</a><ul>";
                    currentSid = sid;
                }

                lit1.Text += "<li><a href=\"timesheet.aspx?u=" + sid + "&ws=" + weekStarting.ToString("yyyy-MM-dd") + "\">" + weekStarting.ToString("MM/dd/yyyy") + "</a></li>";
            }

            if (currentSid != "")
                lit1.Text += "</ul></li>";

            lit1.Text += "</ul>";
            reader.Close();

            command = new SqlCommand("usp_RS_Users", databaseConnection);
            command.CommandType = CommandType.StoredProcedure;

            reader = command.ExecuteReader();

            lit2.Text += "<ul>";

            while (reader.Read())
            {
                string sid = (string)reader["sid"];
                DirectoryEntry userInfo = new DirectoryEntry("LDAP://<SID=" + sid + ">");

                lit2.Text += "<li><a href=\"timesheet.aspx?u=" + sid + "\">" + userInfo.Properties["cn"].Value.ToString() + "</a></li>";
            }

            lit2.Text += "</ul>";

            reader.Close();
            databaseConnection.Close();
        }

        /// <summary>
        /// Checks to see if a the config file has a particular user flagged as an administrator.
        /// </summary>
        /// <param name="logon">
        /// The logon that we are to check.
        /// </param>
        /// <returns>
        /// True if the user is an administrator, false otherwise.
        /// </returns>
        protected static bool IsUserAdministrator(string logon)
        {
            // Check the TimesheetAdministrators app settings entry (if it exists) for the logon that was passed
            // to this function
            if (ConfigurationManager.AppSettings["TimesheetAdministrators"] != null)
            {
                List<string> administrators = new List<string>(ConfigurationManager.AppSettings["TimesheetAdministrators"].ToLower().Split(';'));
                return administrators.Contains(logon.ToLower());
            }

            else
                return false;
        }
    }
}
